<template>
  <div class="panel-container">
    <el-card class="card">
      <template #header>控制面板</template>

      <!-- 工位选择器 -->
      <div class="workstation-selector">
        <div class="section-title">选择工位</div>
        <el-select v-model="selectedWorkstation" placeholder="请选择工位" style="width: 200px;" :loading="loading"
          :disabled="loading || workstations.length === 0" @change="handleWorkstationChange">
          <el-option v-for="workstation in workstations" :key="workstation.id"
            :label="`${workstation.name} (${workstation.status === 'normal' ? '正常' : '异常'})`" :value="workstation.id">
          </el-option>
        </el-select>
        <div v-if="loading" class="loading-text">正在加载工位数据...</div>
        <div v-else-if="workstations.length === 0" class="empty-text">暂无可控工位</div>
      </div>

      <!-- 当前选中工位的控制面板 -->
      <div v-if="selectedWorkstation && currentWorkstation" class="workstation-controls">
        <div class="section-title">{{ currentWorkstation.name }} 控制面板</div>

        <el-row :gutter="16">
          <el-col :span="6">
            <el-card>
              <div class="control-item">
                <div class="control-title">设备电源</div>
                <el-switch v-model="currentWorkstation.power" active-text="开" inactive-text="关"
                  @change="handleDeviceControl('power', $event)" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card>
              <div class="control-item">
                <div class="control-title">灯光</div>
                <el-switch v-model="currentWorkstation.light" active-text="开" inactive-text="关"
                  @change="handleDeviceControl('light', $event)" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card>
              <div class="control-item">
                <div class="control-title">继电器1</div>
                <el-switch v-model="currentWorkstation.relay1" active-text="开" inactive-text="关"
                  @change="handleDeviceControl('relay1', $event)" />
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card>
              <div class="control-item">
                <div class="control-title">继电器2</div>
                <el-switch v-model="currentWorkstation.relay2" active-text="开" inactive-text="关"
                  @change="handleDeviceControl('relay2', $event)" />
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request.js'

// 工位数据
const workstations = ref([])

// 实验室数据
const labData = ref({})

// 加载状态
const loading = ref(false)

// 当前选中的工位ID
const selectedWorkstation = ref(null)

// 初始状态加载标志
const initialLoad = ref(true)

// 获取工位数据
const fetchWorkstationData = async () => {
  try {
    loading.value = true
    const response = await request.get('/env/admin/query')
    const resData = response.data

    console.log("工位数据返回结果:", resData)

    if (resData.state === 200 && resData.data) {
      // 赋值实验室基础数据
      Object.assign(labData.value, resData.data)

      // 清空之前的工位数据
      workstations.value.splice(0, workstations.value.length)

      // 处理工位数据，将后端格式转换为前端格式
      if (resData.data.workstations && resData.data.workstations.length > 0) {
        const processedWorkstations = resData.data.workstations.map(backendWorkstation => ({
          id: backendWorkstation.id,
          name: backendWorkstation.workstationCode,
          code: backendWorkstation.workstationCode,
          status: backendWorkstation.workstationStatus,
          // 将数字状态转换为布尔值 (0=关, 1=开)
          power: backendWorkstation.powerStatus === 1,
          light: backendWorkstation.lightStatus === 1,
          relay1: backendWorkstation.relayNum1Status === 1,
          relay2: backendWorkstation.relayNum2Status === 1,
          // 保存原始状态值以便发送到后端
          powerStatus: backendWorkstation.powerStatus,
          lightStatus: backendWorkstation.lightStatus,
          relayNum1Status: backendWorkstation.relayNum1Status,
          relayNum2Status: backendWorkstation.relayNum2Status,
          // 其他传感器数据
          temperature: backendWorkstation.temperature,
          humidity: backendWorkstation.humidity,
          smokeScope: backendWorkstation.smokeScope,
          flameScope: backendWorkstation.flameScope,
          lightIntensity: backendWorkstation.lightIntensity,
          curUserId: backendWorkstation.curUserId,
          username: backendWorkstation.username,
          realName: backendWorkstation.realName
        }))

        // 清空之前的数据，确保完全替换
        workstations.value.length = 0
        workstations.value.push(...processedWorkstations)

        console.log("刷新后的工位列表数据:", workstations.value)

        // 强制触发响应式更新
        await nextTick()

        console.log("响应式更新后的当前工位状态:", currentWorkstation.value)

        // 如果有工位数据，默认选中第一个
        if (workstations.value.length > 0 && !selectedWorkstation.value) {
          selectedWorkstation.value = workstations.value[0].id
        }

        // 标记初始加载完成
        initialLoad.value = false
      }
    } else {
      ElMessage.error(resData.message || '获取工位数据失败')
    }
  } catch (error) {
    console.error('获取工位数据失败:', error)
    ElMessage.error('获取工位数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 当前选中工位的引用
const currentWorkstation = computed(() => {
  if (!selectedWorkstation.value) return null
  return workstations.value.find(w => w.id === selectedWorkstation.value)
})

// 处理工位选择变更
const handleWorkstationChange = (workstationId) => {
  console.log('选择工位:', workstationId)
  // 这里可以添加一些额外的逻辑，比如记录用户操作等
}


// 设备控制函数
const controlDevice = async (endpoint, params) => {
  try {
    // 构建带查询参数的URL
    const url = new URL(endpoint, request.defaults.baseURL)
    Object.keys(params).forEach(key => {
      url.searchParams.append(key, params[key])
    })

    console.log(`发送请求到: ${url.toString()}`)

    const response = await request.post(url.toString())
    console.log(`${endpoint} 控制响应:`, response.data)
    return response
  } catch (error) {
    console.error(`${endpoint} 控制失败:`, error)
    throw error
  }
}

// 处理设备控制
const handleDeviceControl = async (device, status) => {
  // 如果是初始加载，不发送请求
  if (initialLoad.value) {
    return
  }

  const statusStr = status ? '1' : '0'
  const workstationCode = currentWorkstation.value?.code

  if (!workstationCode) {
    ElMessage.error('未选择有效工位')
    return
  }

  // 根据设备类型映射到后端接口和参数名
  const deviceMapping = {
    power: {
      endpoint: '/workstation/set/powerStatus',
      paramName: 'powerStatus'
    },
    light: {
      endpoint: '/workstation/set/lightStatus',
      paramName: 'lightStatus'
    },
    relay1: {
      endpoint: '/workstation/set/relayNum1Status',
      paramName: 'relayNum1Status'
    },
    relay2: {
      endpoint: '/workstation/set/relayNum2Status',
      paramName: 'relayNum2Status'
    }
  }

  const mapping = deviceMapping[device]
  if (!mapping) {
    ElMessage.error(`未知设备类型: ${device}`)
    return
  }

  try {
    console.log(`发送${device}控制命令: ${status ? '开' : '关'}，工位: ${workstationCode}`)

    // 使用查询参数而不是请求体，因为后端使用@Param注解
    const queryParams = new URLSearchParams({
      workstationCode,
      [mapping.paramName]: statusStr.toString()
    })

    const response = await request.post(`${mapping.endpoint}?${queryParams.toString()}`)

    console.log(`${device}控制响应:`, response.data)

    if (response.data && response.data.state === 200) {
      ElMessage.success(`${response.data.message}`)
    } else {
      throw new Error(response.data?.message || `控制失败`)
    }
  } catch (error) {
    console.error(`控制失败:`, error)
    ElMessage.error(`控制失败: ${error.message}`)

    // 如果控制失败，使用nextTick延迟恢复开关状态，避免重复触发change事件
    await nextTick()
    if (device === 'power') {
      currentWorkstation.value.power = !status
    } else if (device === 'light') {
      currentWorkstation.value.light = !status
    } else if (device === 'relay1') {
      currentWorkstation.value.relay1 = !status
    } else if (device === 'relay2') {
      currentWorkstation.value.relay2 = !status
    }
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchWorkstationData()
})
</script>

<style scoped>
.panel-container {
  padding: 20px;
}

.card {
  width: 100%;
}

.section-title {
  margin-bottom: 16px;
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.workstation-selector {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.workstation-controls {
  margin-bottom: 24px;
}

.control-item {
  text-align: center;
}

.control-title {
  margin-bottom: 12px;
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}


/* 加载和空状态样式 */
.loading-text,
.empty-text {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.empty-text {
  color: #f56c6c;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-col {
    margin-bottom: 16px;
  }

  .workstation-selector {
    padding: 12px;
  }

  .loading-text,
  .empty-text {
    font-size: 11px;
  }
}
</style>
